# Readme:
# use: make config
# use: make dir
# use: make GlobalClean
# use: make clean
# use: make rebuild
# use: make cleanall
# use: make test
# use: make

# firs of all, use "make config" or "make dir" to
# build a source files struct. and then,
# put your source files into the DIR src
# link libs to the DIR lib
# set as a C++ Makefile
# use: ":1,$ s/\.c/\.cpp/g" in vi


SHELL=/bin/sh
CC=g++
MAKE=make
MAKE_DIR=$(PWD)/../

SRC_DIR=$(MAKE_DIR)/src/
SRC_DIR+=$(MAKE_DIR)/test/
OBJ_DIR=$(MAKE_DIR)/obj/

LIB_DIR=$(MAKE_DIR)/

INCLUDE_DIR=$(MAKE_DIR)/
INCLUDE_DIR+=$(MAKE_DIR)/include/
INCLUDE_DIR+=$(MAKE_DIR)/src/

DEBUG_DIR=$(MAKE_DIR)/debug/
RELEASE_DIR=$(MAKE_DIR)/release/

OUTPUT_DIR=
OUTPUT_FILE=test_all

INCLUDE=$(foreach n,$(INCLUDE_DIR),-I$(n))
#INCLUDE+=$(foreach n,$(SRC_DIR),-I$(n))

#LIB=$(foreach n,$(LIB_DIR),-L$(n))
#LIB+=$(foreach n,$(LIB_DIR),-L$(wildcard $(n)lib*.a))
#LIB:=$(notdir $(LIB))
#LIB:=$(patsubst %*.a,%.ddd ,$(LIB))
#LIB:=$(patsubst lib%.a,-l% ,$(LIB) )
#LIB +=-L$(OBJ_DIR)

LIB+=-lgtest
#LIB+=-lavcodec
#LIB+=-Lavutil
#LIB+=-lz

vpath %.h $(INCLUDE_DIR)
vpath %.cpp $(SRC_DIR)
vpath %.o $(OBJ_DIR)
vpath %.d $(OBJ_DIR)

SRC_FILES:=$(foreach n,$(SRC_DIR),$(wildcard $(n)*.cpp))
SRC_FILES:=$(filter-out %main.cpp, $(SRC_FILES))
#SRC_FILES2:=$(SRC_FILES)
SRC_FILES:=$(notdir $(SRC_FILES))
OBJ_FILES:=$(patsubst %.cpp,%.o,$(SRC_FILES) )
DEP_FILES:=$(patsubst %.cpp,%.d,$(SRC_FILES) )

FLAG_DEBUG=-g
FLAG_COMPLE=-c
FLAG_LINK=

DEBUG=1
ifeq ($(DEBUG),1)
OUTPUT_DIR:=$(DEBUG_DIR)
FLAG_COMPLE:=$(FLAG_COMPLE) $(FLAG_DEBUG)
FLAG_LINK:=
else
OUTPUT_DIR:=$(RELEASE_DIR)
FLAG_COMPLE:=$(FLAG_COMPLE) -static
FLAG_LINK:=
endif

OUT=$(OUTPUT_FILE)

$(OUT): $(OBJ_FILES)
	@echo -e "building: $(notdir $@) \n\t please wait ...\n"
	@$(CC) $(FLAG_LINK) $(addprefix $(OBJ_DIR),$(notdir $^)) $(LIB) -o $@
%.o:%.cpp %.d
	@echo -e "building: $(notdir $@) \n\t please wait ...\n"
	@$(CC) $(FLAG_COMPLE) $< $(INCLUDE) -o $(OBJ_DIR)$@
$(OBJ_DIR)%.d:%.cpp
	@echo -e "building: $(notdir $@) \n\t please wait ...\n"
	$(CC) $< $(INCLUDE) -MM -MD -o $@
-include $(addprefix $(OBJ_DIR),$(DEP_FILES))
config: dir
dir:
#        mkdir -p $(SRC_DIR)
	mkdir -p $(OBJ_DIR)
#        mkdir -p $(LIB_DIR)
#        mkdir -p $(INCLUDE_DIR)
	mkdir -p $(DEBUG_DIR)
	mkdir -p $(RELEASE_DIR)
clean:
	@rm -f $(OBJ_DIR)* *.d *.o
	@rm -f $(OUT)
	@clear
rebuild: clean all
cleanall:
	@rm -f $(OBJ_DIR)*
	@rm -f $(RELEASE_DIR)*
	@rm -f $(DEBUG_DIR)*
test:
	$(OUT)

# just for debug this Makefile
djs:
	@echo -e "SRC_FILES: $(SRC_FILES)\n"
	@echo -e "OBJ_FILES: $(OBJ_FILES)\n"
	@echo -e "DEP_FILES: $(DEP_FILES)\n"


.PHONY: all config rebuild test cleanall djs
.SUFFIXES:
GlobalClean:
	@find . -type f -name "Makefile" |sed -n '2,$$p'|sed s/Makefile/\ \`pwd\`/g|awk ' {ECHO="echo"};{CD="cd "};{MAKE="&& make clean&&"};{print ECHO,CD,$$1,MAKE,CD,$$2  } '   |sh
